//
//  QLUserManager.m
//  QLTiyufeng_IOS
//
//  Created by anan on 14-4-8.
//  Copyright (c) 2014年 baobaodev_anan. All rights reserved.
//

#import "QLUserManager.h"

@implementation QLUserManager

-(id)init
{
    self = [super init];
    if (self) {
        self.userInfos = [[NSMutableDictionary alloc] init];
    }
    return self;
}

static QLUserManager *instance;

+(QLUserManager*)shareInstance
{
    if (instance == nil) {
        instance = [[QLUserManager alloc] init];
    }
    return instance;
}

//检测是否是手机号码
+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     */
    NSString * MOBILE = @"^1[3-9]\\d{9}$";
    
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

+ (BOOL)isEmailAddress:(NSString*)email {
    
    NSString *emailRegex = @"^\\w+((\\-\\w+)|(\\.\\w+))*@[A-Za-z0-9]+((\\.|\\-)[A-Za-z0-9]+)*.[A-Za-z0-9]+$";
    
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    
    return [emailTest evaluateWithObject:email];
    
}

//保存登录用户信息，同时保存为最后用户
- (void)saveUserInfo:(NSDictionary*)userInfo
{
    [QLPropertyUtils putDictionaryByKey:@"userInfo" value:userInfo];
}

//本地获取登录用户信息
- (NSDictionary*)getUserInfoFromNative
{
    return [QLPropertyUtils getDictionaryByKey:@"userInfo"];
}

//获取后的用户信息，可能是系统生成的用户
- (NSDictionary*)getLastUserInfoFromNative
{
    return [QLPropertyUtils getDictionaryByKey:@"userInfo"];
}

//保存最后的用户信息
- (void)saveLastUserInfo:(NSDictionary*)dic
{
    [QLPropertyUtils putDictionaryByKey:@"userInfo" value:dic];
}

-(void)userLogout
{
    [QLPropertyUtils putStringByKey:@"imAccount" value:nil];
    [QLPropertyUtils putStringByKey:@"imPassword" value:nil];
    [QLPropertyUtils deleteDictionaryByKey:@"userInfo"];
}

/**
 *  判断是不是登陆用户
 *
 *  @return
 */
- (BOOL)isLoginUser
{
    NSDictionary *dic = [QLPropertyUtils getDictionaryByKey:@"userInfo"];
    return dic==nil?NO:YES;
}

/**
 *  显示登陆窗口
 *
 *  @param block
 */
- (void)showLoginDialog
{

}

- (void)detailWithUserId:(int)userId callback:(QLHttpResultBlock)callback
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic ql_setInterge:userId forKey:@"id"];
    [dic setObject:ApplicationDelegate.currentUserId forKey:@"userId"];
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [requestManager GET:@"http://ping.vsmu.cn/app/Interface/User?type=9001" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        
     //   NSLog(@"%@",dic);
        
        NSDictionary *messageDic = [dic objectForKey:@"MESSAGE_INFO"];
        if ([[messageDic ql_stringForKey:@"CODE"] isEqualToString:@"0000"]) {
            BOOL isMe = NO;
            if (userId==[[self getLastUserInfoFromNative] ql_intForKey:@"ID"]) {
                isMe = YES;
            }
            if (isMe) {
                [self saveLastUserInfo:dic[@"USER_INFO_RSP"][@"USER_INFO"]];
            }
        }
        if (callback) {
            callback(YES,dic[@"USER_INFO_RSP"][@"USER_INFO"]);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (callback) {
            callback(NO,nil);
        }
    }];
}

- (void)updateWithUserId:(int)userId phone:(NSString*)phone name:(NSString*)name headerUrl:(NSString*)headerUrl callback:(QLHttpResultBlock)callback
{
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic ql_setObject:phone forKey:@"PHONE"];
    [dic ql_setObject:name forKey:@"NAME"];
    if (headerUrl==nil||headerUrl.length<1) {
        headerUrl = [userInfo ql_stringForKey:@"headerUrl"];
    }
    [dic ql_setObject:headerUrl forKey:@"head_pic_url"];
    [dic ql_setInterge:[userInfo ql_intForKey:@"ID"] forKey:@"userId"];
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [requestManager GET:@"http://ping.vsmu.cn/app/Interface/User?type=9004" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        if ([[dic[@"MESSAGE_INFO"] ql_stringForKey:@"CODE"] isEqualToString:@"0000"]) {
            [[QLUserManager shareInstance] detailWithUserId:[userInfo ql_intForKey:@"ID"] callback:^(BOOL isCache, id data) {
                callback(isCache,data);
            }];
        }else{
            callback(NO,nil);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        callback(NO,nil);
    }];

}

- (void)users:(NSArray*)list callback:(QLHttpResultBlock)callback
{
    NSString *str = @"http://ping.vsmu.cn/app/Interface/User?type=9008";
    for (NSString *uid in list) {
        str = [NSString stringWithFormat:@"%@&ids=%@",str,uid];
    }
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [requestManager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        NSDictionary *messageDic = [dic objectForKey:@"MESSAGE_INFO"];
        if ([[messageDic ql_stringForKey:@"CODE"] isEqualToString:@"0000"]) {
            NSArray *users = dic[@"USER_INFO_RSP"][@"USER_INFOS"];
            for (NSDictionary *dic in users) {
                [self.userInfos setObject:dic forKey:[dic ql_stringForKey:@"ID"]];
            }
            [QLPropertyUtils putDictionaryByKey:@"userInfos" value:self.userInfos];
        }
        if (callback) {
            callback(NO,dic[@"USER_INFO_RSP"][@"USER_INFOS"]);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (callback) {
            callback(NO,nil);
        }
    }];
}

- (NSString*)userNameWithUserId:(NSString*)userId
{
    if ([userId isEqualToString:@"9194"]) {
        return @"客服";
    }
    if (self.userInfos.count<1) {
        NSDictionary *dic = [QLPropertyUtils getDictionaryByKey:@"userInfos"];
        if (dic&&dic.count>0) {
            self.userInfos = [NSMutableDictionary dictionaryWithDictionary:dic];
        }
    }
    NSDictionary *dic = [self.userInfos objectForKey:userId];
    if (dic==nil) {
        return userId;
    }
    return [dic ql_stringForKey:@"NAME"];
}

- (NSString*)userHeaderWithUserId:(NSString*)userId
{
    if ([userId isEqualToString:@"9194"]) {
        return @"http://a4.mzstatic.com/us/r30/Purple1/v4/c2/34/4b/c2344b6a-0407-3d54-4495-2db2279c1456/icon175x175.jpeg";
    }
    if (self.userInfos.count<1) {
        NSDictionary *dic = [QLPropertyUtils getDictionaryByKey:@"userInfos"];
        if (dic&&dic.count>0) {
            self.userInfos = [NSMutableDictionary dictionaryWithDictionary:dic];
        }
    }
    NSDictionary *dic = [self.userInfos objectForKey:userId];
    if (dic==nil) {
        [self users:[NSArray arrayWithObjects:userId, nil] callback:^(BOOL isCache, id data) {
            
        }];
        return userId;
    }
    return [dic ql_stringForKey:@"HEAD_PIC_URL"];
}

@end
